package com.xs.ahoi.hcxs.utils;

import com.xs.ahoi.hcxs.handler.NotifyProgressHandler;
import com.xs.ahoi.hcxs.model.vo.DownloadProgressVO;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.FileCallBack;
import okhttp3.Call;
import okhttp3.Request;

import java.io.File;

/**
 * 文件下载工具类
 *
 * @author fuhuichao
 * @date 2020-07-14 20:46
 */
public class FileDownloadUtil {

    public static void start(String url, String fileName) {
        String savePath = Constants.FILE_DOWN_PATH_FULL;
        DownloadProgressVO progressVO = new DownloadProgressVO();
        progressVO.setFileName(fileName);

        // 初始化
        NotifyProgressHandler notifyProgressHandler = new NotifyProgressHandler();
        notifyProgressHandler.init(fileName);

        OkHttpUtils
                .get()
                .url(url)
                .build()
                .execute(new FileCallBack(savePath, fileName) {
                    @Override
                    public void onBefore(Request request, int id) {
                        progressVO.setProgressText("等待下载");
                        progressVO.setProgress(0);
                        notifyProgressHandler.pushNotify(progressVO);
                        ToastUtil.show("已创建下载任务");
                    }

                    @Override
                    public void onAfter(int id) {
                        progressVO.setOver(true);
                        progressVO.setProgress(100);
                        progressVO.setProgressText("下载完毕");
                        notifyProgressHandler.pushNotify(progressVO);
                        ToastUtil.show("下载完毕");
                    }

                    @Override
                    public void onError(Call call, Exception e, int id) {
                        progressVO.setProgressText("下载失败：" + e.getMessage());
                        notifyProgressHandler.pushNotify(progressVO);
                        ToastUtil.show("下载失败：" + e.getMessage());
                    }

                    @Override
                    public void onResponse(File response, int id) {
                    }

                    @Override
                    public void inProgress(float progress, long total, int id) {
                        progressVO.setProgressText("下载中");
                        progressVO.setTotalSize(FileUtil.byteToSize(total, 0) + "-");
                        progressVO.setProgress(Double.valueOf(Math.floor(progress * 100)).intValue());
                        notifyProgressHandler.pushNotify(progressVO);
                    }
                });

        LogUtil.e("downloadId started!");
    }
}
